home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
- From: Dan Pop <danpop@mail.cern.ch>
- Newsgroups: comp.lang.c
- Subject: Re: variable length string
- Date: Tue, 6 Feb 1996 00:14:31 +0100
- Organization: CERN European Lab for Particle Physics
- Message-ID: <9602052314.AA18664@dxmint.cern.ch>
- References: <4f5s97$8sho@tigger.cc.uic.edu>
- X-NNTP-Posting-Host: hpl3sn03.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
- X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
-
- Qi Zeng <zeng@sunphy1.phy.uic.edu> writes:
-
- >Hi, I have a question in reading a variable length string:
- >Suppose you want to read from stdin a string, but you do not know how
- >long it will be. You have to assign the string to some char*, to use
- >it say as an element part of node in an linked list.
- > How can you do that? .
-
- Use fgets with a reasonably sized buffer. After reading the string,
- use strlen to find out its real length, malloc the right amount of memory
- and copy the string there (dropping the terminating '\n').
-
- If you want your code to be bullet-proof, check that the last character
- of the string is '\n' indeed. If it isn't, there are more characters to be
- read from stdin. Increase the size of your buffer and repeat the
- operation, appending the new characters to the ones already read in the
- buffer, until the '\n' shows up. This can be easily done if the buffer is
- allocated with malloc and extended with realloc.
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-